package co.yixiang.yshop.module.order.api;

import cn.hutool.core.util.ObjectUtil;
import co.yixiang.yshop.framework.common.enums.OrderInfoEnum;
import co.yixiang.yshop.module.order.api.productorder.ProductOrderApi;
import co.yixiang.yshop.module.order.api.productorder.dto.ProductOrderDTO;
import co.yixiang.yshop.module.order.controller.app.order.vo.AppStoreOrderQueryVo;
import co.yixiang.yshop.module.order.service.storeorder.AppStoreOrderService;
import co.yixiang.yshop.module.order.service.storeorder.AsyncStoreOrderService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

import static co.yixiang.yshop.framework.common.exception.util.ServiceExceptionUtil.exception;
import static co.yixiang.yshop.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static co.yixiang.yshop.module.order.enums.ErrorCodeConstants.ORDER_PAY_FINISH;
import static co.yixiang.yshop.module.order.enums.ErrorCodeConstants.STORE_ORDER_NOT_EXISTS;


@Service
public class ProductOrderApiImpl implements ProductOrderApi {

    @Resource
    @Lazy
    private AppStoreOrderService appStoreOrderService;

    @Resource
    private AsyncStoreOrderService asyncStoreOrderService;

    @Override
    public ProductOrderDTO getPayParam(String orderId) {
//        Long userId = getLoginUserId();
        AppStoreOrderQueryVo orderInfo = appStoreOrderService.getOrderInfo(orderId, null);
        if (ObjectUtil.isNull(orderInfo)) {
            throw exception(STORE_ORDER_NOT_EXISTS);
        }
        if (orderInfo.getPaid().equals(OrderInfoEnum.PAY_STATUS_HAVE_PAID.getValue())) {
            throw exception(ORDER_PAY_FINISH);
        }

        ProductOrderDTO productOrderDTO = new ProductOrderDTO();
        productOrderDTO.setAmount(orderInfo.getPayPrice());
        return productOrderDTO;
    }

    @Override
    public void handleOrder(String orderId, Map<String, String> packageParams) {
        Long userId = getLoginUserId();
        AppStoreOrderQueryVo orderInfo = appStoreOrderService.getOrderInfo(orderId, null);
        appStoreOrderService.updatePayInfo(orderInfo, packageParams);
        // 异步统计
        asyncStoreOrderService.orderData(userId);
    }


    @Override
    public void handleWeChatPayNotify(String orderId, Map<String, String> resultMap) throws Exception {
        appStoreOrderService.wxPayNotify(orderId, resultMap);
    }

    @Override
    public void yuePay(String orderId, Long uid,Boolean helpPay) {
        appStoreOrderService.yuePay(orderId, uid,helpPay);
    }


}
